//
//  LLMainViewController.swift
//  MyEcho
//
//  Created by longlong on 16/1/22.
//  Copyright © 2016年 LongLong. All rights reserved.
//

import UIKit

class LLMainViewController: UIViewController,RACollectionViewDelegateReorderableTripletLayout, RACollectionViewReorderableTripletLayoutDataSource{

    @IBOutlet weak var myCollectionView: UICollectionView!
    var indexPath:NSIndexPath?;
//    var dataArray:NSMutableArray?;
//    self.dataArray?.addObject(music);

    let urlHeaderHome:NSString = "http://echosystem.kibey.com/sound/hot?page=";
    dynamic var urlHeader:NSString = "http://echosystem.kibey.com/sound/hot?page=";
    var page:NSInteger = 1;
    override func viewDidLoad() {
        // 上拉刷新 下拉加载更多
        self.myCollectionView.mj_header = MJRefreshNormalHeader.init(refreshingBlock: { () -> Void in
            self.page=1;
            self.getDataFromNetWork(self.page);
        });
        self.myCollectionView.mj_footer = MJRefreshAutoNormalFooter.init(refreshingBlock: { () -> Void in
            self.getDataFromNetWork(++self.page);
        });
        
        self.addObserver(self,forKeyPath:"urlHeader", options: NSKeyValueObservingOptions.New, context: nil);
        
        setLeftItem();
        getDataFromNetWork(page);
        
    }
    
    @IBAction func goPlayingView(sender: UIBarButtonItem) {
        if GlobalDataObject.sharedInstance.arySave.count==1{
            var goPlayPage = GlobalDataObject.sharedInstance.arySave.firstObject as! LLDetailViewController;
            goPlayPage.isGoPlayingMusic = true;
            self.navigationController?.pushViewController( goPlayPage, animated: true);
        }else{
            let alert =  UIAlertView(title: "提示", message: "没有正在播放的音乐！", delegate: self, cancelButtonTitle: "取消");
            alert.show();
        }
    }
    
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        if keyPath == "urlHeader" {
            page=1;
            getDataFromNetWork(page);
        }
    }
    //侧滑中心按钮
    func setLeftItem(){
        let lefItem = MMDrawerBarButtonItem.init(target: self, action: Selector("leftDrawerButtonPress:"));
        self.navigationItem.setLeftBarButtonItem(lefItem, animated: true);
    }
    
    func leftDrawerButtonPress(sender:UIButton){
        self.mm_drawerController.toggleDrawerSide(MMDrawerSide.Left, animated: true, completion: nil)
    }
    //获取网络数据
    func getDataFromNetWork(page:NSInteger){
        
        AFNetworkReachabilityManager.sharedManager().startMonitoring();
        AFNetworkReachabilityManager.sharedManager().setReachabilityStatusChangeBlock { (status) -> Void in
            switch (status){
            case AFNetworkReachabilityStatus.NotReachable:
                if page == 1 {
                    //本地获取数据
                    let  cacheDir = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory,  NSSearchPathDomainMask.UserDomainMask, true).first
                    let  path = cacheDir?.stringByAppendingString("/store.plist")
                    
                    let dicData =  NSData(contentsOfFile:path!)
                    let dic = try! NSJSONSerialization.JSONObjectWithData(dicData!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
                    self.userDataFromNetwork(dic);
                }
                break
            default :
                self.getDataFromNetWorkOnly(page);
                break;
            }
        }
        
        
    }
    func getDataFromNetWorkOnly(page:NSInteger){
        AFAppDotNetAPIClient.sharedClient().GET(AllDefine.homePageURLWith(page, baseUrl: urlHeader) as String, parameters: nil, success: {(task: NSURLSessionDataTask?, JSON: AnyObject?) -> Void in
            if (JSON is NSDictionary){
                let dic =  JSON as? NSDictionary ;
                if (dic?.objectForKey("message")?.isEqual("success") != nil){
                    if page==1 {
                        let  cacheDir = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory,  NSSearchPathDomainMask.UserDomainMask, true).first
                        let  path = cacheDir?.stringByAppendingString("/store.plist")
                        
                        let  dicData = try! NSJSONSerialization.dataWithJSONObject(dic!, options: NSJSONWritingOptions.PrettyPrinted)
                        dicData.writeToFile(path!, atomically: true)
                    }
                    self.userDataFromNetwork(dic!);

                }
            }else{
                print("主页：获取数据失败")
            }
            
            }) { (task: NSURLSessionDataTask?, error: NSError?) -> Void in
                print("获取数据失败:\(error!)");
        }

    }
    
    func userDataFromNetwork(dic:NSDictionary){
        let ary:NSArray;
        if dic.objectForKey("result")?.objectForKey("data") is NSArray{
            ary = (dic.objectForKey("result")?.objectForKey("data") as? NSArray)!;
        }else{
            ary = (dic.objectForKey("result")?.objectForKey("data")?.objectForKey("sounds") as? NSArray)!;
        }
//        if self.urlHeader == self.urlHeaderHome{
//            ary = (dic.objectForKey("result")?.objectForKey("data") as? NSArray)!;
//        }else{
//            ary = (dic.objectForKey("result")?.objectForKey("data")?.objectForKey("sounds") as? NSArray)!;
//        }
        if page==1{
            GlobalDataObject.sharedInstance.arrayData.removeAllObjects();
            self.myCollectionView.mj_header.endRefreshing();
        }else{
            self.myCollectionView.mj_footer.endRefreshing();
        }
        
        for var inDic in ary{
            let music:Music = Music();
            music.setValuesForKeysWithDictionary(inDic as! [String : AnyObject]);
            GlobalDataObject.sharedInstance.arrayData.addObject(music);
        }
        self.myCollectionView.reloadData();
        print("主页：获取数据成功");

    }
    
    //MARK: UICollectionViewDataSource
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return 1;
    }

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{
        return (GlobalDataObject.sharedInstance.arrayData.count);
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cellID = "cellID";
        let cell:LLMaincell = collectionView.dequeueReusableCellWithReuseIdentifier(cellID, forIndexPath: indexPath) as! LLMaincell;
        let url = NSURL.init(string:((GlobalDataObject.sharedInstance.arrayData.objectAtIndex(indexPath.row)) as! Music).pic_200 as String);
        cell.imageView.sd_setImageWithURL(url, placeholderImage:UIImage.init(named: "default"));
        return cell;

    }
    
    //MARK: UICollectionViewDelegate
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        collectionView.deselectItemAtIndexPath(indexPath, animated: true);
        self.indexPath = indexPath;
        GlobalDataObject.sharedInstance.currentIndex = indexPath.row;
        GlobalDataObject.sharedInstance.isFromNetWork = true;
        if GlobalDataObject.sharedInstance.arySave.count==1{
            self.navigationController?.pushViewController( GlobalDataObject.sharedInstance.arySave.firstObject as! UIViewController, animated: true);
        }else{
            self.performSegueWithIdentifier("GoPlay", sender: nil);
        }
    }
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if(segue.identifier == "GoPlay"){
            let theSegue = segue.destinationViewController;
            GlobalDataObject.sharedInstance.arySave.addObject(theSegue)
        }
    }
    

    //MARK:RACollectionViewDelegateReorderableTripletLayout
    func sectionSpacingForCollectionView(collectionView: UICollectionView!) -> CGFloat {
        return 2.0
    }
    func minimumInteritemSpacingForCollectionView(collectionView: UICollectionView!) -> CGFloat {
        return 2.0
    }
    func minimumLineSpacingForCollectionView(collectionView: UICollectionView!) -> CGFloat {
        return 2.0
    }
    /** 占位图*/
    func reorderingItemAlpha(collectionview: UICollectionView!) -> CGFloat {
        return 0.3;
    }
    
    /** 能否拖拽 插入*/
    func collectionView(collectionView: UICollectionView!, itemAtIndexPath fromIndexPath: NSIndexPath!, canMoveToIndexPath toIndexPath: NSIndexPath!) -> Bool {
        return true;
    }
    
    /** 能否拖拽*/
    func collectionView(collectionView: UICollectionView, canMoveItemAtIndexPath indexPath: NSIndexPath) -> Bool {
        return true;
    }
    
}


//func insetsForCollectionView(collectionView: UICollectionView!) -> UIEdgeInsets {
//    return UIEdgeInsetsMake(5.0, 0, 5.0, 0);
//}
//func autoScrollTrigerEdgeInsets(collectionView: UICollectionView!) -> UIEdgeInsets {
//    return UIEdgeInsetsMake(50.0, 0, 50.0, 0)
//}
//func autoScrollTrigerPadding(collectionView: UICollectionView!) -> UIEdgeInsets {
//    return UIEdgeInsetsMake(64.0, 0, 0, 0);
//}
